<?php
/**
 * Created by PhpStorm.
 * User: Sky
 * Date: 16/8/4
 * Time: 下午3:16
 */

namespace app\models;


use app\librarys\DbCacheUtility;
use app\librarys\Tools;

class Open
{
    public static function getConfig($institutionCode)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM t_open_config WHERE institution_code=:institutionCode');
        $cmd->bindValue(':institutionCode', $institutionCode);
        $item = $cmd->queryOne();
        if ($item == false) {
            return null;
        } else {
            return $item;
        }
    }

    public static function getConfigByAccount($account)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM t_open_config WHERE account=:account');
        $cmd->bindValue(':account', $account);
        $item = DbCacheUtility::queryOne($cmd, 60 * 10);
        if ($item == false) {
            return null;
        } else {
            return $item;
        }
    }

    public static function setConfig($data)
    {
        $cmd = \Yii::$app->db->createCommand('CALL p_set_open_config(:in_institution_code, :in_account, :in_token, :in_is_user_open, :in_user_login_url, :in_is_integral_open, :in_set_integral_url, :in_set_order_url,:in_is_agent)');
        $cmd->bindValue(':in_institution_code', $data['institution_code']);
        $cmd->bindValue(':in_account', $data['account']);
        $cmd->bindValue(':in_token', $data['token']);
        $cmd->bindValue(':in_is_user_open', $data['is_user_open']);
        $cmd->bindValue(':in_user_login_url', $data['user_login_url']);
        $cmd->bindValue(':in_is_integral_open', $data['is_integral_open']);
        $cmd->bindValue(':in_set_integral_url', $data['set_integral_url']);
        $cmd->bindValue(':in_set_order_url', $data['set_order_url']);
        $cmd->bindValue(':in_is_agent', $data['is_agent']);

        $id = $cmd->queryScalar();
        return $id;
    }

    /**
     * 判断是否有相同的account
     * @param $account
     * @return bool
     */
    public static function isExistsAccount($account)
    {
        $sql = 'SELECT count(1) FROM t_open_config WHERE account = :account';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':account', $account);
        $result = $cmd->queryScalar();
        if ($result > 0) {
            return true;
        }
        return false;
    }

    /**
     * 生成account
     * @return string
     */
    public static function createAccount()
    {
        $account = Tools::getRandomString(8);
        $isExists = self::isExistsAccount($account);
        if ($isExists) {
            self::createAccount();
        }
        return $account;
    }
}